package com.iwhalecloud.citybrain.flow.platform.manager.application.utils;

import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.ManagementService;
import org.flowable.engine.common.api.variable.VariableContainer;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author SiJiang
 * @createTime 2021/7/30 11:08 下午
 * @description
 */
@Slf4j
public class ParseRenderedVariable {
    /**
     * 变量渲染
     * @param origin 未经渲染的语句
     * @param variables 要渲染的变量名与变量值构成的键值对
     * @return 经过渲染的语句
     */
    public static String parseRenderedVariable(String origin, Map<String,Object> variables){
        String pattern = "\\$\\{\\w+\\}";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(origin);
        while (m.find()) {
            String findResult = m.group(0).trim();
            // 去除${}
            findResult = findResult.substring(2,findResult.length()-1);
            // 从变量中匹配
            String matchVariable = "";
            Object result = variables.get(findResult);
            if (Objects.nonNull(result)){
                matchVariable = String.valueOf(result);
            }
            // 替换变量
            origin = origin.replaceAll("\\$\\{"+findResult+"}", URLUtil.encode(matchVariable, StandardCharsets.UTF_8));

        }
        return origin;
    }


    public static String parseRenderedVariable(String origin, VariableContainer variableContainer){
        String pattern = "\\$\\{\\w+(\\.\\w+)*\\}";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(origin);
        ManagementService managementService = SpringUtils.getBean(ManagementService.class);
        while (m.find()) {
            String findResult = m.group(0).trim();
            Object value = null;

            try {
                ExpressionCmd expressionCmd = new ExpressionCmd(findResult,variableContainer);
                value = managementService.executeCommand(expressionCmd);
            } catch (Exception e) {
                log.error(String.format("解析表达式异常，表达式= %s，变量= %s",findResult, JSON.toJSONString(variableContainer)));
            }
            String matchVariable = null;
            if (Objects.nonNull(value)){
                matchVariable = String.valueOf(value);
            }

            if (StringUtils.isNotBlank(matchVariable)){
                //去除${}
                findResult = findResult.substring(2,findResult.length()-1);
                // 替换变量
                origin = origin.replaceAll("\\$\\{"+findResult+"}", URLUtil.encode(matchVariable, StandardCharsets.UTF_8));
            }

        }
        return origin;
    }

}
